/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.healthecology.data.http;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Optional;

/**
 * Enum for http request type
 */
public enum HttpRequestType {
    /**
     * Http get request
     */
    REQUEST_GET {
        @Override
        public Optional<Request> buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) {
            return Optional.of(requestBuilder.get().build());
        }
    },

    /**
     * Http post request
     */
    REQUEST_POST {
        @Override
        public Optional<Request> buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) {
            return Optional.ofNullable(requestBody)
                .map(data -> RequestBody.create(data, JSON))
                .map(body -> requestBuilder.post(body).build());
        }
    },

    /**
     * Http put request
     */
    REQUEST_PUT {
        @Override
        public Optional<Request> buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) {
            return Optional.ofNullable(requestBody)
                .map(data -> RequestBody.create(data, JSON))
                .map(body -> requestBuilder.put(body).build());
        }
    },

    /**
     * Http delete request
     */
    REQUEST_DELETE {
        @Override
        public Optional<Request> buildRequest(@Nullable String requestBody, @NotNull Request.Builder requestBuilder) {
            return Optional.of(Optional.ofNullable(requestBody)
                .map(data -> RequestBody.create(data, JSON))
                .map(body -> requestBuilder.delete(body).build())
                .orElse(requestBuilder.delete().build()));
        }
    },
    ;

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * To build a valid http request
     *
     * @param requestBody The request body
     * @param requestBuilder The builder with url value inserted
     * @return A Request
     */
    public abstract Optional<Request> buildRequest(
        @Nullable String requestBody, @NotNull Request.Builder requestBuilder);
}
